package montecarlo.single.thread;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import montecarlo.european.option.EuropeanOption;
import montecarlo.gui.MonteCarloGui;

public class MonteCarloSingleThread {

	double time;
	//Monte Carlo function
	public Double MonteCarloStandardOption(	String CallPutFlag,double S,double X,double T,
			double r,double b,double v,int nSteps, int nSimulations){
		//start time
		final long start = System.nanoTime();

			Double dt,St, Sum, Drift, vSqrdt;
			int i, j, z;
			Random rnd=new Random();
			Sum=0.0;
			z=0;
			dt = T/nSteps ;
			Drift = (b - Math.pow(v, 2) / 2) * dt;
			vSqrdt = v * Math.sqrt(dt);
			if (CallPutFlag.equals("c")){
				z = 1;
			}
						
			else if (CallPutFlag.equals("p")){
				z=-1;
			}
						
			for (i=0;i<nSimulations;i++){
				St=S;
				for (j=0; j<nSteps;j++){
					St=St*Math.exp(Drift + vSqrdt * rnd.nextGaussian());
					
				}
				Sum= Sum+Math.max(z*(St-X), 0);
			}
			//end time	
		    final long end = System.nanoTime();
		    //time taken
		    time= (end - start)/1.0e9;			
			return Math.exp(-r*T)*(Sum/nSimulations);
				
		}
	
	public static ArrayList <EuropeanOption> readValues() throws IOException {
	    final BufferedReader reader = 
	      new BufferedReader(new FileReader("european-options.txt"));
	    
	    final ArrayList <EuropeanOption> options = new  ArrayList <EuropeanOption> ();
	    
	    String option = null;
	    while((option = reader.readLine()) != null) {
	      final String[] values = option.split(",");
	      EuropeanOption eo = new EuropeanOption(
	    		  values[0],Double.valueOf(values[1]),Double.valueOf(values[2]),Double.valueOf(values[3]),
	    		  Double.valueOf(values[4]),Double.valueOf(values[5]),Double.valueOf(values[6]),
	    		  Integer.valueOf(values[7]),Integer.valueOf(values[8]));
	
	      
	     options.add(eo); 
	    }

	    return options;    
	  }
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			ArrayList <EuropeanOption> options = readValues();
			MonteCarloGui gui = new MonteCarloGui(options, "single");
			gui.setVisible(true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public double getTime() {
		return time;
	}


	

}
